package com.sh.data.engine.domain.common.service.impl;

import com.sh.data.engine.common.util.HttpClientUtil;
import com.sh.data.engine.domain.common.service.DistributedService;
import com.sh.data.engine.domain.datadev.offline.model.enums.OfflineDevTaskStopEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;

@Service
@Slf4j
public class DistributedServiceImpl implements DistributedService {

    // 避免客户服务器ip获取失败，通过配置纠正
    @Value("${data.engine.localHostIp:}")
    private String localHostIp;

    @Override
    public boolean stopTaskPost(String remoteIp, Map<String, String> paramMap, int code) {
        String localHost = null;
        try {
            InetAddress inetAddress = InetAddress.getLocalHost();
            localHost = inetAddress.getHostAddress();
        } catch (UnknownHostException e) {
            log.info("获取本地ip失败{}", e.getMessage());
        }
        String localHostIp = this.localHostIp;
        if (StringUtils.isNotBlank(localHostIp)) {
            localHost = localHostIp;
        }
        if (!localHost.equalsIgnoreCase(remoteIp)) {
            String url = generateURl(remoteIp, code);
            HttpClientUtil.doPost(url, paramMap);
            return true;
        }
        return false;
    }

    private String generateURl(String remoteIp, int code) {
        String url = OfflineDevTaskStopEnum.of(code).getUrl();
        StringBuilder sb = new StringBuilder();
        sb.append("http://");
        sb.append(remoteIp);
        sb.append(":8081");
        sb.append("/api/v1");
        sb.append(url);
        return sb.toString();
    }

    @Override
    public boolean stopTaskGet(String remoteIp, Map<String, String> paramMap, int code) {
        String localHost = null;
        try {
            InetAddress inetAddress = InetAddress.getLocalHost();
            localHost = inetAddress.getHostAddress();
        } catch (UnknownHostException e) {
            log.info("获取本地ip失败{}", e.getMessage());
        }
        String localHostIp = this.localHostIp;
        if (StringUtils.isNotBlank(localHostIp)) {
            localHost = localHostIp;
        }
        if (!localHost.equalsIgnoreCase(remoteIp)) {
            HttpClientUtil.doGet(OfflineDevTaskStopEnum.of(code).getUrl(), paramMap);
            return true;
        }
        return false;
    }

    @Override
    public String getCurrentIpInfo() {

        InetAddress inetAddress = null;
        try {
            inetAddress = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            log.info("获取本地IP失败{}");
        }
        String localHost = inetAddress.getHostAddress();
        return localHost;
    }
}
